/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Platform,
    InteractionManager,
    TouchableWithoutFeedback,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import ImageCropPicker from 'react-native-image-crop-picker';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
import LoadingModal from '../components/LoadingModal';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class AddAnimals extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.shopId = '';
        this.state = {
            staturs:this.props.navigation.state.params.staturs,
            month_birth:'',//月龄
            cate:'',//品种
            num:'',//库存
            num_danger:'',//库存警戒值
            price:'',//价格
            get_price:'',//进价
            user_id:'',//用户id
            imgUriList:[],
            imgDataList:[],
            id:this.props.navigation.state.params.id || '',
            animalData:{},
            is_show:1,
            load:false,
        }; 
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                InteractionManager.runAfterInteractions(() => {
                    if($this.state.staturs=='编辑活体'){
                        $this.getAnimalData();
                    }
                });              
            }).catch(err=> {
                console.log(err)
            });
    }
    // 渲染上架下架按钮
    renderButton(){
        if(this.state.is_show==1){
            return(
                <View>
                    <TouchableOpacity onPress={()=>this.buttonClick()} style={styles.buttonBox}>
                        <View style={[styles.button,{backgroundColor:'#FF0000'}]}>
                            <Text style={{color:'#fff'}}>下架</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            )
        }else if(this.state.is_show==2){
            return(
                <View>
                    <TouchableOpacity onPress={()=>this.buttonClick()} style={styles.buttonBox}>
                        <View style={[styles.button,{backgroundColor:'#0894ED'}]}>
                            <Text style={{color:'#fff'}}>上架</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            )
        }
    }
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={this.state.staturs} 
                    leftPress={()=>this.toBack()}
                    rightText={this.state.staturs=='添加活体'?'':'完成'}
                    rightTextStyle={{color:'#fff'}}
                    rightTextPress={()=>this.finished()}/>
                <LoadingModal visible={this.state.load} onRequestClose={()=>{console.log('666')}}/>
                <ScrollView>
                    <View style={styles.addImgBox}>
                        <TouchableOpacity onPress={()=>this.choseImg()}>
                            <ImageWrapper width={80} height={80} icon={this.state.imgUriList.length>0?{uri:this.state.imgUriList[0].path}:'addImg'}/>
                        </TouchableOpacity>
                    </View>
                    <View style={{paddingLeft:10,backgroundColor:'#fff',borderBottomWidth:1,borderBottomColor:'#ccc'}}>
                        <GoodsItem 
                            style={styles.itemBorder} 
                            title={'月龄'} 
                            hasInput={true}
                            placeholder={'请输入月龄'} 
                            defaultValue={this.state.month_birth} 
                            onChangeText={(text)=>this.getMonthBirth(text)}
                            onBlur={()=>this.editAnimalData('month_birth')}/>
                        
                        <GoodsItem 
                            style={styles.itemBorder} 
                            title={'品种'} 
                            hasInput={true}
                            placeholder={'请输入品种'}  
                            defaultValue={this.state.cate} 
                            onChangeText={(text)=>this.getCate(text)}
                            onBlur={()=>this.editAnimalData('cate')}/>
                        <GoodsItem 
                            style={styles.itemBorder} 
                            title={'库存'} 
                            hasInput={true}
                            placeholder={'请输入库存'} 
                            defaultValue={this.state.num} 
                            onChangeText={(text)=>this.getNum(text)}
                            onBlur={()=>this.editAnimalData('num')}/>
                        <GoodsItem 
                            style={styles.itemBorder} 
                            title={'库存警戒值'} 
                            hasInput={true}
                            placeholder={'请输入库存警戒值'} 
                            defaultValue={this.state.num_danger} 
                            onChangeText={(text)=>this.getNumDager(text)}
                            onBlur={()=>this.editAnimalData('num_danger')}/>
                        <GoodsItem 
                            style={styles.itemBorder} 
                            title={'售价'} 
                            hasInput={true}
                            placeholder={'请输入价格'} 
                            defaultValue={this.state.price} 
                            onChangeText={(text)=>this.getPrice(text)}
                            onBlur={()=>this.editAnimalData('price')}/>
                        <GoodsItem 
                            title={'采购价'} 
                            hasInput={true}
                            placeholder={'请输入采购价'} 
                            defaultValue={this.state.get_price} 
                            onChangeText={(text)=>this.getBuyPrice(text)}
                            onBlur={()=>this.editAnimalData('get_price')}/>
                    </View>
                    <View style={{marginTop:20,marginBottom:20}}>
                        {this.state.staturs=='添加活体'?<TouchableOpacity style={styles.buttonBox} onPress={()=>this.addButton()}>
                            <View style={[styles.button,{backgroundColor:'#0894ED'}]}>
                                <Text style={{color:'#fff'}}>发布</Text>
                            </View>
                        </TouchableOpacity>:this.renderButton()}
                    </View>

                </ScrollView>
                
            </View>
        )

    }
    // 返回按钮
    toBack(){
        this.props.navigation.state.params.backUpData();
        this.props.navigation.goBack();
    }
    /*
    * 编辑商品时右上角完成按钮
    */
    finished(){
        this.toBack();
    }
    // 获取月龄
    getMonthBirth(text){
        this.setState({
            month_birth:text.replace(/\s/g,'')
        })
    }
    // 获取品种
    getCate(text){
        this.setState({
            cate:text.replace(/\s/g,'')
        })
    }
    // 获取库存
    getNum(text){
        this.setState({
            num:text.replace(/\s/g,'')
        })
    }
    // 获取库存警戒值
    getNumDager(text){
        this.setState({
            num_danger:text.replace(/\s/g,'')
        })
    }
    // 获取售价
    getPrice(text){
        this.setState({
            price:text.replace(/\s/g,'')
        })
    }
    // 获取采购价
    getBuyPrice(text){
        this.setState({
            get_price:text.replace(/\s/g,'')
        })
    }
    // 编辑是获取活体数据
    getAnimalData(){
        var $this = this;
        shopService.myReleaseLivingIdInfo(function(data){
            if(data.code==10000){
                var obj = data.data[0];
                var arr = [];
                var imgObj = {};
                imgObj.path = 'http://peita.oss-cn-beijing.aliyuncs.com/'+obj.sl_img;
                arr[0] = imgObj;
                $this.setState({
                    month_birth:obj.month_birth,//月龄
                    cate:obj.cate,//品种
                    num:obj.num,//库存
                    num_danger:obj.num_danger,//库存警戒值
                    price:obj.price,//价格
                    get_price:obj.get_price,//进价
                    imgUriList:arr,
                    imgDataList:arr,
                    animalData:obj,
                    is_show:obj.is_show,
                })
            }
        },$this.state.id,$this.token)
    }
    // 编辑时调用修改接口
    editAnimalData(name){
        if(this.state.staturs=='编辑活体'){
            var $this = this;
            var typeObj = {
                'month_birth':2,
                'cate':3,
                'num':4,
                'num_danger':5,
                'price':6,
                'get_price':7,
                'is_show':8,
            }
            if(this.state.animalData[name]!=this.state[name].replace(/\s/g,'')){
                var params = {};
                params.sl_id = this.state.id;
                params.type = typeObj[name];
                params[name] = this.state[name].replace(/\s/g,'');
                shopService.myReleaseLivingIdSave(function(data){
                    // alert(JSON.stringify(data))
                    if(data.code==10000){
                        console.log('666')
                    }
                },params,[],$this.token)
            }
        }        
    }
    // 选择头像上传
    async choseImg(){
        var $this = this;
        ImageCropPicker.openPicker({
            width: 300, 
            height: 300, 
            cropping: true,
            mediaType:'photo',
        }).then(image => { 
            var source = {};
            if (Platform.OS === 'android') {
                source = {path: image.path, isStatic: true};
            } else {
                source = {path: image.path.replace('file://', ''), isStatic: true};
            }
            // 
            var uriArr = $this.state.imgUriList;
            uriArr[0] = source;
            var dataArr = $this.state.imgDataList;
            dataArr[0] = image;
            this.setState({
                imgUriList:uriArr,
                imgDataList:dataArr,
            });
            if($this.state.staturs=='编辑活体'){
                var params = {};
                params.sl_id = $this.state.id;
                params.type = 1;
                var arr = [];
                arr['sl_img'] = image.path;
                shopService.upFile(function(data){
                    if(data.code==10000){
                        params['sl_img'] = data.data;
                        shopService.myReleaseLivingIdSave(function(data){
                            if(data.code==10000){
                                console.log('666');
                            }
                        },params,[],$this.token)
                    }
                },arr,$this.token)
                
            }
        }).catch((err)=> {
                console.log(err);
            });
    }

    //点击发布按钮事件
    addButton(){
        var $this = this;
        var imgArr = [];
        if(this.state.month_birth=='请输入月龄'||this.state.month_birth==''||this.state.month_birth==0){
            alert('请输入月龄！');
            return;
        }else if(this.state.cate=='请输入品种'||this.state.cate==''||this.state.cate==0){
            alert('请输入品种！');
            return;
        }else if(this.state.num=='请输入库存'||this.state.num==''||this.state.num==0){
            alert('请输入库存！');
            return;
        }else if(this.state.num_danger=='请输入库存警戒值'||this.state.month_birth==''||this.state.month_birth==0){
            alert('请输入库存警戒值！');
            return;
        }else if(this.state.price=='请输入价格'||this.state.month_birth==''||this.state.month_birth==0){
            alert('请输入价格！');
            return;
        }else if(this.state.get_price=='请输入进价'||this.state.month_birth==''||this.state.month_birth==0){
            alert('请输入进价！');
            return;
        }else if(this.state.imgDataList.length==0){
            alert('请添加头像！');
            return;
        }else{
            this.setState({
                load:true
            })
            imgArr['img'] = this.state.imgDataList[0].path;
            shopService.addLiving(function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    $this.setState({
                        load:false
                    })
                    Alert.alert(
                        '提示信息',
                        '发布成功',
                        [{text: '确定', onPress: () => $this.toBack()}])
                }
            },$this.state.month_birth,$this.state.cate,$this.state.num,$this.state.num_danger,$this.state.price,$this.state.get_price,$this.userId,$this.shopId,imgArr,$this.token)
        }
        
    }
    // 上架下架按钮点击事件
    buttonClick(){
        var $this = this;
        var params = {};
        params.type = 8;
        params.sl_id = $this.state.id;
        if(this.state.is_show==1){
            params.is_show = 2;
        }else if(this.state.is_show==2){
            params.is_show = 1;
        }
        shopService.myReleaseLivingIdSave(function(data){
            alert(JSON.stringify(data));
            if(data.code==10000){
                $this.setState({
                    is_show:params.is_show
                })
            }
        },params,[],$this.token)
    }
}


const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    },
    addImgBox:{
        justifyContent:'center',
        alignItems:'center',
        height:100,
        backgroundColor:'#EFEFF4',
        borderBottomWidth:1,
        borderBottomColor:'#E1E1E4'
    },
    button:{
        width:3*width/4,
        borderRadius:5,
        justifyContent:'center',
        alignItems:'center',
        height:40
    },
    buttonBox:{
        alignItems:'center'
    },
    itemBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2'
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.4)',
        justifyContent:'center',
        alignItems:'center',
    },
    
});